package com.cch.android.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cch.android.activity.view.ChooseImageManagerActivity;
import com.cch.android.activity.view.UGallery;
import com.cch.android.imageutil.ImageUtil;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;

public class PuzzleImageActivity extends Activity implements OnClickListener,OnTouchListener{
	
	private Button add_image_btn,home_btn,save_btn,more_bg,add_image_btn_2;
	
	private LinearLayout bg_lay,gallery_puzzle_lay;
	
	private UGallery gl;
	
    private AbsoluteLayout ab;
    
    private ImageView bgImageView;
    
    private Bitmap bgImage;
    
    private Bitmap bmpSet;
	
	private ArrayList<Bitmap>  bmpList;
	
	private ArrayList<Bitmap> scalBmpList;
	
//	private HashMap<Integer,Integer>  viewIntMap;
	
	private HashMap<Integer,ImageView>  viewMap;
	
	private ArrayList<String> imagePathList;
	
	private Context context;
	
	private boolean flag = false;
	
	private int rawX,rawY;
	
	/**
	 * 存放新坐标位置
	 */
	private HashMap<Integer,Integer> rawXMap;
	
	/**
	 * 存放新坐标位置
	 */
	private HashMap<Integer,Integer> rawYMap;
	
	private int bmp_w=0;
	
	private int bmp_h=0;
	
	private int m_screenWidth,m_screenHeight;
	
	private int[] imageIDs={
			R.drawable.puzzle_pg_a,R.drawable.puzzle_pg_b,R.drawable.puzzle_pg_c,R.drawable.puzzle_pg_d,
			R.drawable.puzzle_pg_e,R.drawable.puzzle_pg_f};
	
	private int[] imageIDs_title={
			R.drawable.puzzle_pg_a_a,R.drawable.puzzle_pg_b_b,R.drawable.puzzle_pg_c_c,R.drawable.puzzle_pg_d_d,
			R.drawable.puzzle_pg_e_e,R.drawable.puzzle_pg_f_f};
	private String[] nameIDs;
	
	/**
	 * 存放图片 view
	 */
	
	private HashMap<Integer,View> mapView = new HashMap<Integer,View>();
	
	  @Override
	   public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_puzzle);
		context = this;
		m_screenWidth = Constant.m_screenWidth;
		m_screenHeight = Constant.m_screenHeight;
		Intent intent = getIntent();
		imagePathList = intent.getStringArrayListExtra("chooseimagelist");
		if(imagePathList!=null){
			MyLog.log("图片拼图数量："+imagePathList.size());
			if(bmpList==null)bmpList=new ArrayList<Bitmap>();
			else bmpList.clear();
			if(scalBmpList==null)scalBmpList=new ArrayList<Bitmap>();
			else scalBmpList.clear();
			
		int size = imagePathList.size();
		    for (int i=0;i<size;i++) {
				Bitmap bmp = Constant.getDrawable(imagePathList, i, 1);
				bmpList.add(bmp);
			}
		}
		initView();
	}
	  private void initView(){
		  add_image_btn = (Button)findViewById(R.id.setimage2_add_image);
		  home_btn = (Button)findViewById(R.id.setimage1_home_btn);
		  save_btn = (Button)findViewById(R.id.setimage1_save_btn);
		  more_bg = (Button)findViewById(R.id.setimage2_change_bg);
		  add_image_btn_2 = (Button)findViewById(R.id.setimage2_add_image_2);
		  ab = (AbsoluteLayout)findViewById(R.id.puzzle_image);
		  bg_lay= (LinearLayout)findViewById(R.id.setimage2_change_bg_lay);
		  gallery_puzzle_lay= (LinearLayout)findViewById(R.id.gallery_puzzle_lay);
		  
		  bgImageView = (ImageView)findViewById(R.id.puzzle_image_bg);
		  
		if (bmpList != null) {
//			if(viewIntMap==null)viewIntMap = new HashMap<Integer, Integer>();
//			else viewIntMap.clear();
			if(viewMap==null)viewMap = new HashMap<Integer, ImageView>();
			else viewMap.clear();
			
			if(rawXMap==null)rawXMap = new HashMap<Integer, Integer>();
			else rawXMap.clear();
			
			if(rawYMap==null)rawYMap = new HashMap<Integer, Integer>();
			else rawYMap.clear();
			
			
			bgImage = ImageUtil.decodeBitmap(R.drawable.puzzle_pg_a,context);
			
			android.widget.AbsoluteLayout.LayoutParams params = new android.widget.AbsoluteLayout.LayoutParams(android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT,
					android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, (m_screenWidth-bgImage.getWidth())/2, 
					  (m_screenHeight-bgImage.getHeight())/2);
			bgImageView.setLayoutParams(params);
			
			bgImageView.setImageBitmap(bgImage);
			
			nameIDs=new String[]{
					getString(R.string.puzzle_a),getString(R.string.puzzle_b),getString(R.string.puzzle_c),
					getString(R.string.puzzle_d),getString(R.string.puzzle_e),getString(R.string.puzzle_f),getString(R.string.puzzle_g)};
			//Gallery 初始化
			gl = (UGallery) this.findViewById(R.id.gallery_puzzle);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
			lp.setMargins(-(Constant.m_screenWidth/2+150), 0, 0, 0);
			gl.setLayoutParams(lp);
			
			
			galleryAdapter ba = new galleryAdapter();

			ba.addDataInt(imageIDs_title);
			ba.addDataStr(nameIDs);
			gl.setAdapter(ba);
			gl.setOnItemClickListener(lomeListener);
			bg_lay.setVisibility(View.VISIBLE);
			add_image_btn.setVisibility(View.GONE);
			 more_bg.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					bg_lay.setVisibility(View.GONE);
					gallery_puzzle_lay.setVisibility(View.VISIBLE);
					
				}
			});
			int size = bmpList.size();
			int x = 0;
			int y = 0;
			int rotate = 0;
			for (int j = 0; j < size; j++) {
				ImageView im = new ImageView(context);
				switch (j) {
				case 0:
					x = m_screenWidth/4-12;
					y = m_screenHeight/4+10;
					bmp_w =130;
					bmp_h = 230;
					rotate = -4;
					break;
				case 1:
					x = m_screenWidth/2+10;
					y = m_screenHeight/4+20;
					bmp_w = 150;
					bmp_h = 150;
					rotate = 12;
					break;
				case 2:
					x = m_screenWidth/4-10;
					y = m_screenHeight/2+30;
					bmp_w = 200;
					bmp_h = 120;
					rotate =-10;
					break;
				case 3:
					x = m_screenWidth/2+10;;
					y = m_screenHeight/2+50;
					bmp_w = 120;
					bmp_h = 180;
					rotate = 8;
					break;
				}
				android.widget.AbsoluteLayout.LayoutParams params2 = new android.widget.AbsoluteLayout.LayoutParams(
						android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT,
						x, y);
				im.setLayoutParams(params2);
				
				rawXMap.put(j,x);
				
				rawYMap.put(j,y);
				
				//缩放图片
				Bitmap bmpNew = ImageUtil.scalBitmap(bmpList.get(j),bmp_w,bmp_h, rotate);
				scalBmpList.add(bmpNew);
				im.setImageBitmap(bmpNew);
				im.setOnTouchListener(this);
				im.setId(j);
				MyLog.log("imageView v 的id"+im.getId());
				viewMap.put(j, im);
				ab.addView(im);
			}
			
			
			
		}else{
			  Bitmap bmp = ImageUtil.decodeBitmap(R.drawable.icon_free_show, context);
			  
			  android.widget.AbsoluteLayout.LayoutParams params = new android.widget.AbsoluteLayout.LayoutParams(android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, 
					  android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, (m_screenWidth-bmp.getWidth())/2, 
					  (m_screenHeight-bmp.getHeight())/2);
			  bgImageView.setLayoutParams(params);
		}
		  add_image_btn.setOnClickListener(this);
		  home_btn.setOnClickListener(this);
		  save_btn.setOnClickListener(this);
		  add_image_btn_2.setOnClickListener(this);
		 
	  }
	  OnItemClickListener lomeListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				bgImage = ImageUtil.decodeBitmap(imageIDs[arg2],context);
				gallery_puzzle_lay.setVisibility(View.GONE);
				bg_lay.setVisibility(View.VISIBLE);
				switch (arg2) {
				case 0://原图
					 if (bgImage != null)
					bgImageView.setImageBitmap(bgImage);
					break;
	             case 1:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
					break;
	             case 2:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
	 				break;
	             case 3:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
	 				break;
	             case 4:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
	 				break;
	             case 5:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
	 				break;
	             case 6:
	            	 if (bgImage != null)
	            		 bgImageView.setImageBitmap(bgImage);
	 				break;
				}
			}
		};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setimage2_add_image:
		case R.id.setimage2_add_image_2:
			Intent intent = new Intent();
			intent.setClass(this, ChooseImageManagerActivity.class);
			startActivity(intent);
			break;

		case R.id.setimage1_home_btn:
			finish();
			break;
		case R.id.setimage1_save_btn:
			if(scalBmpList!=null){
			bmpSet = doodle(bgImage,scalBmpList);
			bgImageView.setImageBitmap(bmpSet);
			if(bmpSet!=null)
				try {
					Constant.fileName = "puzzle_image";
					String filePath = Constant.saveMyBitmap2("cch_"+Constant.fileName, 100, bmpSet);
					Toast toast = Toast.makeText(getApplicationContext(),
						     getString(R.string.save_image_path)+filePath, Toast.LENGTH_LONG);
						   toast.setGravity(Gravity.CENTER, 0, 0);
						   toast.show();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
			}
			break;
		}
		
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bmpList != null&&!bmpList.isEmpty()) {
			for (Bitmap m : bmpList) {
				if (!m.isRecycled())
					m.recycle();
				System.gc();
			}
			bmpList.clear();
			bmpList = null;
		}
		if(imagePathList!=null&&!imagePathList.isEmpty()){
			imagePathList.clear();
			imagePathList=null;
			}
		if(scalBmpList!=null&&!scalBmpList.isEmpty()){
			for (Bitmap m : scalBmpList) {
				if (!m.isRecycled())
					m.recycle();
				System.gc();
			}
			scalBmpList.clear();
			scalBmpList=null;
			}
		if(bgImage!=null){
			if(!bgImage.isRecycled())bgImage.recycle();
			System.gc();
		}
		if(viewMap!=null){viewMap.clear();viewMap=null;}
		if(rawXMap!=null){rawXMap.clear();rawXMap=null;}
		if(rawYMap!=null){rawYMap.clear();rawYMap=null;}
		if(bmpSet!=null)bmpSet.recycle();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int viewId = v.getId();
		switch (event.getAction()) {

		case MotionEvent.ACTION_DOWN:
			flag = true;
			break;
		case MotionEvent.ACTION_MOVE:
			// flag为true即控件被点到时，执行移动控件操作
			if (flag) {
				rawX = (int) event.getRawX();
				rawY = (int) event.getRawY();
				int scalbmp_m = scalBmpList.get(viewId).getWidth();
				int scalbmp_h = scalBmpList.get(viewId).getHeight();

				// 得到X，Y座标
				android.widget.AbsoluteLayout.LayoutParams params = new android.widget.AbsoluteLayout.LayoutParams(android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, 
						android.widget.AbsoluteLayout.LayoutParams.WRAP_CONTENT, 
						rawX-scalbmp_m/2, rawY-scalbmp_h/2);
				if (v != null)
					v.setLayoutParams(params);
				// 设置最终位置

			}
			break;
		case MotionEvent.ACTION_UP:
			// 手指离开屏幕时，把flag设为false
			rawXMap.put(viewId, rawX);
			
			rawYMap.put(viewId,rawY);
			flag = false;
			break;
		}
		return true;
	}
	class galleryAdapter extends BaseAdapter{
		private int[] dataInt;
		private String[] dataStr;
		
		private void addDataInt(int[] dataInt){
			if(this.dataInt!=null)this.dataInt=null;
			this.dataInt = dataInt;
		}
		
		private void addDataStr(String[] dataStr){
			if(this.dataStr!=null)this.dataStr=null;
			this.dataStr = dataStr;
		}

		@Override
		public int getCount() {
			return this.dataInt!=null? this.dataInt.length:0;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View view = View.inflate(context, R.layout.modle_setimage_effect_grallery_item, null);
			ImageView galleryImageIv = (ImageView)view.findViewById(R.id.setimage1_effect_gallery_image);
			TextView textIv = (TextView)view.findViewById(R.id.setimage1_effect_gallery_text);
			String textStr = dataStr[arg0];
			LinearLayout.LayoutParams  lp = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
			if(textStr.length()==2){
			
			    lp.setMargins(20, 0, 0, 0);
			
			}else if(textStr.length()==3){
				
				lp.setMargins(9, 0, 0, 0);
			}else if(textStr.length()>=4){
				lp.setMargins(4, 0, 0, 0);
			}
			
			textIv.setLayoutParams(lp);
			textIv.setText(textStr);
			galleryImageIv.setImageResource(dataInt[arg0]);
			galleryImageIv.setScaleType(ImageView.ScaleType.FIT_XY);
			
			mapView.put(arg0, galleryImageIv);
			
			return view;
		}
		
	}
	/** 
     * 组合涂鸦图片和源图片 
     * @param src 源图片 
     * @param watermark 涂鸦图片 
     * @return 
     */  
    public Bitmap doodle(Bitmap src, ArrayList<Bitmap> bmpList)  
    {  
        // 另外创建一张图片  
        Bitmap newb = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图  
        Canvas canvas = new Canvas(newb);  
        
        int canW = src.getWidth();
        int canH = src.getHeight();
        
        canvas.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入原图片src  
        int size = bmpList.size();
        for (int i=0;i<size;i++) {
        	 Bitmap bitmap = bmpList.get(i);
        	 int scalbmp_m = bmpList.get(i).getWidth();
			 int scalbmp_h = bmpList.get(i).getHeight();
			 int X = rawXMap.get(i)-scalbmp_m/2;
	         int Y = rawYMap.get(i)-scalbmp_h/2;
        	 int w = X * canW/m_screenWidth;
     		 int h = Y *canH/m_screenHeight;
        	 canvas.drawBitmap(bitmap, w, h, null); // 涂鸦图片画到原图片中间位置  
             canvas.save(Canvas.ALL_SAVE_FLAG);  
             canvas.restore();  
             viewMap.get(i).setVisibility(View.GONE);
		}
        for (Bitmap bitmap : bmpList) {
            if(bitmap!=null)
            	bitmap.recycle();
		}
        return newb;  
    }  
}
